<template>
  <view class="points-page">
    <!-- 积分总览 -->
    <view class="points-overview">
      <view class="points-card">
        <view class="points-main">
          <text class="points-amount">{{ userStore.points }}</text>
          <text class="points-label">当前积分</text>
        </view>
        <view class="points-icon">⭐</view>
      </view>
      
      <view class="points-stats">
        <view class="stat-item">
          <text class="stat-number">{{ userStore.totalPoints }}</text>
          <text class="stat-label">累计获得</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ usedPoints }}</text>
          <text class="stat-label">已使用</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ expiredPoints }}</text>
          <text class="stat-label">已过期</text>
        </view>
      </view>
    </view>
    
    <!-- 积分规则 -->
    <view class="rules-section">
      <view class="section-header" @click="toggleRules">
        <text class="section-title">积分规则</text>
        <text class="toggle-icon" :class="{ expanded: showRules }">{{ showRules ? '▼' : '▶' }}</text>
      </view>
      
      <view v-if="showRules" class="rules-content">
        <view class="rule-item">
          <text class="rule-title">获得积分</text>
          <text class="rule-desc">• 充值：每充值1元获得1积分</text>
          <text class="rule-desc">• 消费：每消费1元获得1积分</text>
          <text class="rule-desc">• 签到：每日签到获得5-20积分</text>
          <text class="rule-desc">• 邀请：邀请好友注册获得100积分</text>
        </view>
        
        <view class="rule-item">
          <text class="rule-title">使用积分</text>
          <text class="rule-desc">• 100积分 = 1元代金券</text>
          <text class="rule-desc">• 积分可在积分商城兑换礼品</text>
          <text class="rule-desc">• 积分有效期为获得后12个月</text>
        </view>
      </view>
    </view>
    
    <!-- 积分记录 -->
    <view class="records-section">
      <view class="section-header">
        <text class="section-title">积分记录</text>
        <picker 
          mode="selector" 
          :range="filterOptions" 
          :value="filterIndex"
          @change="onFilterChange"
        >
          <view class="filter-btn">
            <text class="filter-text">{{ filterOptions[filterIndex] }}</text>
            <text class="filter-arrow">▼</text>
          </view>
        </picker>
      </view>
      
      <scroll-view 
        class="records-list" 
        scroll-y 
        refresher-enabled 
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="loadMore"
      >
        <view v-if="filteredRecords.length === 0" class="empty-state">
          <view class="empty-icon">📝</view>
          <text class="empty-title">暂无积分记录</text>
          <text class="empty-desc">快去消费或充值获得积分吧</text>
        </view>
        
        <view v-else>
          <view 
            v-for="record in filteredRecords" 
            :key="record.id"
            class="record-item"
          >
            <view class="record-icon" :class="getRecordTypeClass(record.type)">
              <text class="icon">{{ getRecordIcon(record.type) }}</text>
            </view>
            
            <view class="record-content">
              <text class="record-title">{{ record.title }}</text>
              <text class="record-desc">{{ record.description }}</text>
              <text class="record-time">{{ formatTime(record.createdAt, 'MM-DD HH:mm') }}</text>
            </view>
            
            <view class="record-amount" :class="{ positive: record.amount > 0 }">
              <text class="amount-text">{{ record.amount > 0 ? '+' : '' }}{{ record.amount }}</text>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <text class="load-text">加载更多...</text>
        </view>
        
        <!-- 没有更多 -->
        <view v-else-if="filteredRecords.length > 0" class="no-more">
          <text class="no-more-text">没有更多记录了</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { formatTime, showError, showSuccess } from '@/utils/common'

const userStore = useUserStore()

// 响应式数据
const showRules = ref(false)
const filterIndex = ref(0)
const refreshing = ref(false)
const hasMore = ref(true)
const pointsRecords = ref([])

// 筛选选项
const filterOptions = ['全部', '获得', '使用', '过期']

// 模拟数据
const usedPoints = ref(150)
const expiredPoints = ref(50)

// 计算属性
const filteredRecords = computed(() => {
  if (filterIndex.value === 0) return pointsRecords.value
  
  const filterMap = {
    1: 'earn',    // 获得
    2: 'spend',   // 使用
    3: 'expire'   // 过期
  }
  
  const filterType = filterMap[filterIndex.value]
  return pointsRecords.value.filter(record => record.type === filterType)
})

// 方法
const toggleRules = () => {
  showRules.value = !showRules.value
}

const onFilterChange = (e) => {
  filterIndex.value = e.detail.value
}

const getRecordTypeClass = (type) => {
  const classMap = {
    earn: 'type-earn',
    spend: 'type-spend',
    expire: 'type-expire'
  }
  return classMap[type] || ''
}

const getRecordIcon = (type) => {
  const iconMap = {
    earn: '⬆️',
    spend: '⬇️',
    expire: '⏰'
  }
  return iconMap[type] || '📝'
}

const onRefresh = async () => {
  refreshing.value = true
  try {
    // 模拟刷新
    await new Promise(resolve => setTimeout(resolve, 500))
    showSuccess('刷新成功')
  } catch (error) {
    showError('刷新失败')
  } finally {
    refreshing.value = false
  }
}

const loadMore = () => {
  if (!hasMore.value) return
  
  // 模拟加载更多
  setTimeout(() => {
    if (pointsRecords.value.length >= 50) {
      hasMore.value = false
    } else {
      // 添加更多记录
      const moreRecords = generateMockRecords(10)
      pointsRecords.value.push(...moreRecords)
    }
  }, 500)
}

const generateMockRecords = (count = 20) => {
  const records = []
  const types = ['earn', 'spend', 'expire']
  const titles = {
    earn: ['充值奖励', '消费奖励', '签到奖励', '邀请奖励', '活动奖励'],
    spend: ['兑换代金券', '积分商城消费', '会员升级'],
    expire: ['积分过期']
  }
  
  for (let i = 0; i < count; i++) {
    const type = types[Math.floor(Math.random() * types.length)]
    const titleList = titles[type]
    const title = titleList[Math.floor(Math.random() * titleList.length)]
    
    let amount = 0
    if (type === 'earn') {
      amount = Math.floor(Math.random() * 100) + 10
    } else if (type === 'spend') {
      amount = -(Math.floor(Math.random() * 50) + 10)
    } else {
      amount = -(Math.floor(Math.random() * 20) + 5)
    }
    
    records.push({
      id: Date.now() + i,
      type,
      title,
      description: getRecordDescription(type, title, Math.abs(amount)),
      amount,
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000)
    })
  }
  
  return records.sort((a, b) => b.createdAt - a.createdAt)
}

const getRecordDescription = (type, title, amount) => {
  const descriptions = {
    '充值奖励': `充值获得${amount}积分`,
    '消费奖励': `消费获得${amount}积分`,
    '签到奖励': `每日签到获得${amount}积分`,
    '邀请奖励': `邀请好友获得${amount}积分`,
    '活动奖励': `参与活动获得${amount}积分`,
    '兑换代金券': `使用${amount}积分兑换代金券`,
    '积分商城消费': `积分商城消费${amount}积分`,
    '会员升级': `会员升级消费${amount}积分`,
    '积分过期': `${amount}积分已过期`
  }
  
  return descriptions[title] || `${title} ${amount}积分`
}

// 生命周期
onMounted(() => {
  if (!userStore.isLoggedIn) {
    uni.showModal({
      title: '请先登录',
      content: '查看积分明细需要先登录账户',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          uni.navigateBack()
        }
      }
    })
    return
  }
  
  // 初始化积分记录
  pointsRecords.value = generateMockRecords(20)
})
</script>

<style lang="scss" scoped>
.points-page {
  min-height: 100vh;
  background: var(--color-background);
  padding: 16px;
}

// 积分总览
.points-overview {
  margin-bottom: 16px;
}

.points-card {
  background: linear-gradient(135deg, #FFD700, #FFA500);
  border-radius: var(--radius-xl);
  padding: 24px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
  box-shadow: 0 4px 16px rgba(255, 215, 0, 0.3);
}

.points-main {
  flex: 1;
}

.points-amount {
  font-size: 36px;
  font-weight: bold;
  display: block;
  margin-bottom: 4px;
}

.points-label {
  font-size: 14px;
  opacity: 0.9;
}

.points-icon {
  font-size: 48px;
  opacity: 0.8;
}

.points-stats {
  background: white;
  border-radius: var(--radius-xl);
  padding: 16px;
  display: flex;
  justify-content: space-around;
  box-shadow: var(--shadow-sm);
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--color-text-secondary);
}

// 区域标题
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
}

// 积分规则
.rules-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.toggle-icon {
  font-size: 14px;
  color: var(--color-text-secondary);
  transition: transform var(--transition-normal);

  &.expanded {
    transform: rotate(90deg);
  }
}

.rules-content {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border);
}

.rule-item {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

.rule-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 8px;
}

.rule-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  line-height: 1.5;
  display: block;
  margin-bottom: 4px;
}

// 筛选按钮
.filter-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: var(--color-background);
  border-radius: var(--radius-md);
  transition: all var(--transition-normal);

  &:active {
    background: var(--color-border);
  }
}

.filter-text {
  font-size: 14px;
  color: var(--color-text-primary);
}

.filter-arrow {
  font-size: 10px;
  color: var(--color-text-secondary);
}

// 积分记录
.records-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  box-shadow: var(--shadow-sm);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.records-list {
  flex: 1;
  max-height: 60vh;
}

.record-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border);

  &:last-child {
    border-bottom: none;
  }
}

.record-icon {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;

  &.type-earn {
    background: rgba(52, 199, 89, 0.1);
    color: var(--color-success);
  }

  &.type-spend {
    background: rgba(255, 149, 0, 0.1);
    color: var(--color-warning);
  }

  &.type-expire {
    background: rgba(142, 142, 147, 0.1);
    color: var(--color-text-secondary);
  }
}

.record-content {
  flex: 1;
}

.record-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 4px;
}

.record-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  display: block;
  margin-bottom: 4px;
}

.record-time {
  font-size: 12px;
  color: var(--color-text-tertiary);
}

.record-amount {
  text-align: right;
}

.amount-text {
  font-size: 18px;
  font-weight: bold;
  color: var(--color-text-secondary);

  .record-amount.positive & {
    color: var(--color-success);
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: var(--color-text-tertiary);
  margin-bottom: 16px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  line-height: 1.5;
}

// 加载状态
.load-more,
.no-more {
  text-align: center;
  padding: 20px;
}

.load-text,
.no-more-text {
  font-size: 14px;
  color: var(--color-text-secondary);
}

// 响应式适配
@media (max-width: 375px) {
  .points-page {
    padding: 12px;
  }

  .points-card {
    padding: 20px;
  }

  .points-amount {
    font-size: 32px;
  }

  .points-icon {
    font-size: 40px;
  }

  .points-stats {
    padding: 12px;
  }

  .stat-number {
    font-size: 18px;
  }

  .rules-section,
  .records-section {
    padding: 16px;
  }

  .record-item {
    padding: 12px 0;
  }

  .record-icon {
    width: 36px;
    height: 36px;
    border-radius: 18px;
    font-size: 14px;
  }

  .record-title {
    font-size: 15px;
  }

  .amount-text {
    font-size: 16px;
  }
}
</style>
